package com.yuke.cloud.service.omc.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.omc.exceptions.OmcBizException;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoExDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.GoodsAndSpecInfoDto;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.dto.StorageSpecInfoDto;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.omc.dto.CartInfoDto;
import com.yuke.cloud.service.omc.dto.CartSpecDto;
import com.yuke.cloud.service.omc.dto.OrderProdDto;
import com.yuke.cloud.service.omc.entity.OdsShopCart;
import com.yuke.cloud.service.omc.service.OdsShopCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by zys on 2018/11/15.
 */
@Api(value = "WEB - OdsShopCartController", tags = "处理OdsShopCart相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/ods/shop_cart")
public class OdsShopCartController extends BaseController {
    @Resource
    private OdsShopCartService odsShopCartService;
    @Autowired
    private SmcFeignApi smcFeignApi;

    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;

    @Autowired
    private PmcFeignApi pmcFeignApi;

    @PostMapping
    @Synchronized
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "odsShopCart", value = "该数据记录的POJO") @RequestBody JSONObject jsonObject) {
        System.out.println("新增一条记录:"+jsonObject.toJSONString());
        Object carts = jsonObject.get("carts");
        List<Map> carts1 = (List<Map>) carts;
        Integer num = 0;
        Long shopId = 0L;
        for (Map map : carts1) {  // todo 每次只传过来一个数据，清空购物车时有多条数据
            System.out.println(map.get("specid"));
            OdsShopCart odsShopCart = new OdsShopCart();
            odsShopCart.setUserId(Long.valueOf(map.get("userid").toString()));
            odsShopCart.setSpecId(Long.valueOf(map.get("specid").toString()));

            List<OdsShopCart> select = odsShopCartService.select(odsShopCart);

            if (Integer.valueOf(map.get("num").toString()) >= 0){
                num = Integer.valueOf(map.get("num").toString());
            }else{
                return WrapMapper.error("非法操作！");
            }
            // add by wg 20190715
            if (map.get("cartType") != null) {
                odsShopCart.setCartType(Byte.valueOf(map.get("cartType").toString()));
            } else {
                odsShopCart.setCartType((byte)1);
            }
            if (map.get("storageId") != null) {

                odsShopCart.setStorageId(Long.valueOf(map.get("storageId").toString()));
            } else {

                List<StorageSpecInfoDto> storageSpecInfoDtoList = wmcStorageFeignApi.getWmsSpecInfoBySpecIds(Arrays.asList(odsShopCart.getSpecId()),shopId);
                if (storageSpecInfoDtoList != null && storageSpecInfoDtoList.size()>0){
                    odsShopCart.setStorageId(storageSpecInfoDtoList.get(0).getStorageId());
                }else{
                    odsShopCart.setStorageId(0L);
                }

            }

            shopId = Long.valueOf(map.get("shopid").toString());
            // add by wg 20190717
            // todo 对于购物车类型为用户的，需要APP前端将商品所在仓库ID发过来 add 20190717
            if (map.get("warehouseId") != null) {
                odsShopCart.setWarehouseId(Long.valueOf(map.get("warehouseId").toString()));
            }else{
                odsShopCart.setWarehouseId(6L);
            }

            if (select.size() < 1) {
                if (num.intValue() == 0) {
                    odsShopCartService.deleteById(odsShopCart.getId());
                    return WrapMapper.ok();
                } else if (num.intValue() > 0) {

                    List<OdsShopCart>list=new ArrayList<>();
                    odsShopCart.setNum(num);
                    odsShopCart.setCreateTime(new Date());
                    odsShopCart.setShopId(shopId);
                    System.out.println("执行新增商品入购物车："+odsShopCart);
                    list.add(odsShopCart);

                    odsShopCartService.bitchsave(list);
                   // return WrapMapper.ok();
                }

            } else {
                odsShopCart.setNum(num);
                odsShopCart.setShopId(shopId);
                Wrapper result = xiugai(odsShopCart);
                if (result.getCode() != 200) {
                    return result;
                }
            }
        }
        return WrapMapper.ok();
    }


    @PostMapping("/xiugai")
    public Wrapper xiugai(@RequestBody OdsShopCart odsShopCart1) {

        System.out.println(odsShopCart1);
        // 根据店铺获取所在城市的商品库存量
        Integer stockCnt = 0;
        if (odsShopCart1.getShopId() != null && odsShopCart1.getNum() > 0) {
            // 获取店名
            List<Long> listShopIds = new ArrayList<>();
            listShopIds.add(odsShopCart1.getShopId());
            System.out.println("oDS+++++++++odsshopcartcontroller=++++++++listShopIds="+listShopIds);
            List<ShopInfoDto> shopInfoDtoList = smcFeignApi.getShopInfoByShopIds(listShopIds);

            if (shopInfoDtoList != null && shopInfoDtoList.size() > 0) {
                List<Long> specIds = new ArrayList<>();
                specIds.add(odsShopCart1.getSpecId());

                Long localWarehouseId = null;
                if (specIds.size() > 0) {
                    // add by wg 20190716 获取商品仓库相关信息
                    Boolean bLocalSpec = true;
                    if (odsShopCart1.getCartType() == 1) {

                        Wrapper wrapperRet = wmcStorageFeignApi.getwarehouseidbyshopid(odsShopCart1.getShopId());

                        if (wrapperRet != null  && wrapperRet.getResult() != null) {

                            localWarehouseId = Long.valueOf(wrapperRet.getResult().toString());

                        } else {
                            throw new OmcBizException(ErrorCodeEnum.GL99990002);
                        }

                        if (localWarehouseId != null && odsShopCart1.getWarehouseId()!= null && localWarehouseId.equals(odsShopCart1.getWarehouseId())) {
                            bLocalSpec = true;
                        } else {
                            bLocalSpec = false;
                        }
                    }

                    if (bLocalSpec) {

                        Wrapper<Map<Long, Integer>> stockCount = wmcStorageFeignApi.getCityStockCount(shopInfoDtoList.get(0).getRegionCityId(), specIds);
                        logger.info("库存="+stockCount);
                        if (stockCount != null && stockCount.getCode() == 200) {
                            Map<Long, Integer> stockCountMap = stockCount.getResult();
                            stockCnt = stockCountMap.get(Long.valueOf(odsShopCart1.getSpecId()));

                        }
                    } else {

                        Wrapper<Map<Long, Integer>> stockCount = wmcStorageFeignApi.getWarehouseStockCount(odsShopCart1.getWarehouseId(), specIds);

                        if (stockCount != null && stockCount.getCode() == 200) {
                            Map<Long, Integer> stockCountMap = stockCount.getResult();
                            stockCnt = stockCountMap.get(Long.valueOf(odsShopCart1.getSpecId()));

                        }
                    }
                }
            }

            // todo

            if (stockCnt != null && stockCnt < odsShopCart1.getNum()) {
                System.out.println("库存不足，无法添加该商品到购物车！");
                return WrapMapper.error("库存不足，无法添加该商品到购物车！");
            }
        }

        OdsShopCart odsShopCart = new OdsShopCart();
        odsShopCart.setUserId(odsShopCart1.getUserId());
        odsShopCart.setSpecId(odsShopCart1.getSpecId());
        odsShopCart.setCartType(odsShopCart1.getCartType());  // add by wg 20190715
        List<OdsShopCart> select = odsShopCartService.select(odsShopCart);

        if (select != null && select.size() > 0) {
            OdsShopCart odsShopCart2 = select.get(0);
            Long id = odsShopCart2.getId();
            odsShopCart.setId(id);
            odsShopCart.setNum(odsShopCart1.getNum());
            if (odsShopCart1.getNum().toString().equals("0")) {
                // mod by wg 20190329 直接批量删除掉所有符合条件的购物车
                odsShopCartService.batchDelete(select);

            } else {
                int i=0;
                for (OdsShopCart item:select) {
                    if (i == 0){
                        odsShopCart.setId(item.getId());
                        odsShopCart.setShopId(odsShopCart1.getShopId());
                        odsShopCart.setCartType(odsShopCart1.getCartType()); // add by wg 20190715
                        odsShopCart.setWarehouseId(odsShopCart1.getWarehouseId());
                        odsShopCart.setStorageId(odsShopCart1.getStorageId());
                        odsShopCartService.update(odsShopCart);
                    }else{
                        odsShopCartService.deleteById(item.getId());
                    }
                   i++;
                }

            }
        } else if (select == null || select.size() == 0) {  // 新增

            odsShopCart.setNum(odsShopCart1.getNum());
            odsShopCart.setCreateTime(new Date());
            odsShopCart.setShopId(odsShopCart1.getShopId());
            odsShopCart.setCartType(odsShopCart1.getCartType()); // add by wg 20190715
            odsShopCart.setWarehouseId(odsShopCart1.getWarehouseId());
            odsShopCart.setStorageId(odsShopCart1.getStorageId());
            odsShopCartService.save(odsShopCart);
        }
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        odsShopCartService.deleteById(id);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<OdsShopCart> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        OdsShopCart odsShopCart = odsShopCartService.findById(id);
        return WrapMapper.ok(odsShopCart);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<OdsShopCart>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                               @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<OdsShopCart> list = odsShopCartService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @GetMapping("/foruser/{id}")
    @ApiOperation(httpMethod = "GET", value = "获取所有记录")
    public Wrapper<CartInfoDto> list2(@ApiParam(name = "id", value = "记录") @PathVariable Long id,
                                      @ApiParam(name = "shopId", value = "店铺", defaultValue = "0") @RequestParam(defaultValue = "0") Long shopId,
                                      @ApiParam(name = "cartType", value = "购物车类型", defaultValue = "1") @RequestParam(defaultValue = "1") Byte cartType) {


        //cmcFeignApi.loadSecKillAndSpecs();
        CartInfoDto cartInfoDto = new CartInfoDto();
        cartInfoDto.setUserId(id);
        List<CartSpecDto> cartSpecDtos = new ArrayList<>();
        cartInfoDto.setCartSpecDtos(cartSpecDtos);

        // mod by wg 20190410 修改成可以根据店铺及用户返回购物车
        Example example = new Example(OdsShopCart.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("create_time desc");
        criteria.andEqualTo("userId", id);
        criteria.andEqualTo("cartType", cartType);
         List<OdsShopCart> list = odsShopCartService.selectByExample(example);
        if (list.size() == 0) {
            return WrapMapper.ok(cartInfoDto);
        }


        List<Long> specIds = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {

            OdsShopCart odsShopCart = list.get(i);


            specIds.add(odsShopCart.getSpecId());

            CartSpecDto cartSpecDto = new CartSpecDto();
            cartSpecDto.setSpecId(odsShopCart.getSpecId());
            cartSpecDto.setNum(odsShopCart.getNum());
            cartSpecDto.setShopId(odsShopCart.getShopId());
            cartSpecDtos.add(cartSpecDto);
        }

        Wrapper<List<ProdSpecInfoExDto>> result = pmcFeignApi.getSpecBySpecIds(shopId, specIds, cartType);

        if (result != null && result.getCode() == 200) {
            List<ProdSpecInfoExDto> prodSpecInfoExDtos = result.getResult();

            if (prodSpecInfoExDtos != null && prodSpecInfoExDtos.size() > 0) {
                for (ProdSpecInfoExDto prodSpecInfoExDto : prodSpecInfoExDtos) {
                    for (CartSpecDto cartSpecDto : cartSpecDtos) {
                        if (cartSpecDto.getSpecId().equals(prodSpecInfoExDto.getSpecId())) {
                            cartSpecDto.setProdSpecInfoExDto(prodSpecInfoExDto);
                            cartInfoDto.setCartSpecDtos(cartSpecDtos);
                            //break;
                        }
                    }
                }
            }
        }

        List<CartSpecDto> cartSpeclist = new ArrayList<>();
        cartInfoDto.getCartSpecDtos().stream().collect(Collectors.groupingBy(CartSpecDto::getSpecId)).forEach((k, kList) ->
        {
            CartSpecDto aaa = new CartSpecDto();
            IntSummaryStatistics nmap = kList.stream().collect(Collectors.summarizingInt(e->Integer.valueOf(e.getNum().toString())));

            aaa.setSpecId(kList.get(0).getSpecId());
            aaa.setNum(Integer.valueOf(String.valueOf(nmap.getSum())));
            aaa.setProdSpecInfoExDto(kList.get(0).getProdSpecInfoExDto());
            aaa.setSpecFrom(kList.get(0).getSpecFrom());
            cartSpeclist.add(aaa);

        });



        cartInfoDto.setCartSpecDtos(cartSpeclist);

        return WrapMapper.ok(cartInfoDto);
    }


    @PostMapping("/batchdelete")
    public Wrapper batchdelete(@RequestBody JSONObject jsonObject) {

        Long userId = Long.valueOf(jsonObject.get("userId").toString());
        Long shopId = Long.valueOf(jsonObject.get("shopId").toString());
        odsShopCartService.batchDeleteByShopAndUser(userId, shopId);

        return WrapMapper.ok("success");
    }

}
